import { h, onMounted, reactive, ref, toRaw } from "vue";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "../utils/types";
import { addDialog } from "@/components/ReDialog";
import { deviceDetection } from "@pureadmin/utils";
import editForm from "../form.vue";
import { message } from "@/utils/message";
import { ElMessageBox } from "element-plus";
import {
  getMaterialUnitListApi,
  createMaterialUnitApi,
  updateMaterialUnitApi,
  delMaterialUnitApi,
  getMaterialUnitShowApi,
  updateStatusMaterialUnitApi
} from "@/api/materialApi";
export function usePage() {
  const form = reactive({
    page: 1,
    perPage: 10,
    name: null
  });
  const formRef = ref();
  const dataList = ref([]);
  const isShow = ref(false);
  const loading = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const indexMethod = (index: number) => {
    return index + 1;
  };
  const getStatusType = (type, text = false) => {
    switch (type) {
      case 1:
        return text ? "启用" : "primary";
      case 2:
        return text ? "禁用" : "danger";
    }
  };
  const switchLoadMap = ref({});
  const columns: TableColumnList = [
    {
      label: "ID",
      prop: "materialUnitId",
      width: 80
    },
    {
      label: "单位名称",
      prop: "name",
	  minWidth: 100
    },
    {
      label: "单位编码",
      prop: "code",
	  minWidth: 150
    },
    
	{
		label: "创建者",
		prop: "createUser.username",
		minWidth: 100
	},
	{
		label: "创建时间",
		prop: "createdAt",
		minWidth: 140
	},
	{
		label: "更新者",
		prop: "updateUser.username",
		minWidth: 100
	},
	{
		label: "更新时间",
		prop: "updatedAt",
		minWidth: 140
	},
	{
	  label: "状态",
	  prop: "status",
	  cellRenderer: scope => (
	    <el-switch
	      size={scope.props.size === "small" ? "small" : "default"}
	      loading={switchLoadMap.value[scope.index]?.loading}
	      v-model={scope.row.status}
	      active-value={1}
	      inactive-value={2}
	      active-text="启用"
	      inactive-text="禁用"
	      inline-prompt
	      onChange={() => switchChange(scope as any)}
	    />
	  )
	},
	{
	  label: "备注",
	  prop: "remarks"
	},
    
    {
      label: "操作",
      fixed: "right",
      slot: "operation",
	  width: 180
    }
  ];
  function switchChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.status === 2 ? "禁用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.name
      }</strong>吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        setTimeout(() => {
          switchLoadMap.value[index] = Object.assign(
            {},
            switchLoadMap.value[index],
            {
              loading: false
            }
          );
          updateStatusMaterialUnitApi({
            materialUnitId: row.materialUnitId,
            status: row.status
          }).then((res) => {
  			if(res.code === 200) {
  				message("操作成功!", {
  				  type: "success"
  				});
				onSearch()
  			}
            
          });
        }, 300);
      })
      .catch(() => {
        row.status === 1 ? (row.status = 2) : (row.status = 1);
      });
  }
  function handleSizeChange(val: number) {
    loading.value = true;
    form.page = 1;
    form.perPage = val;
    getMaterialUnitListApi(toRaw(form)).then(res => {
      dataList.value = res.result.list;
      pagination.total = res.result.total;
      pagination.pageSize = res.result.perPage*1;
      pagination.currentPage = 1;
    });

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  function handleCurrentChange(val: number) {
    loading.value = true;
    form.page = val;
    getMaterialUnitListApi(toRaw(form)).then(res => {
      dataList.value = res.result.list;
      pagination.total = res.result.total;
	  pagination.pageSize = res.result.perPage*1;
	  pagination.currentPage = val;
    });

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  async function onSearch() {
    loading.value = true;
    const { result } = await getMaterialUnitListApi(toRaw(form));
    dataList.value = result.list;
    pagination.total = result.total;
    pagination.pageSize = result.perPage*1;
    pagination.currentPage = result.page*1;

    setTimeout(() => {
      loading.value = false;
    }, 150);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    form.name = null;
    formEl.resetFields();
    onSearch();
  };
  const formInline = ref();
  async function openDialog(title = "新增", row?: FormItemProps) {
    if (`${title}` == "新增") {
      formInline.value = {
        title: "新增",
        status: 1,
        code: 'UNIT' + (new Date()).toLocaleString().replace(/[:/ ]/g, ''),
      };
    } else {
      const res = await getMaterialUnitShowApi({
        materialUnitId: row?.materialUnitId
      });
	  if(res.code !== 200) {
	  	message(res.msg ?? "操作失败,请联系管理员", {
	  	  type: "error"
	  	});
	  	return
	  }
      formInline.value = {
        title: "修改",
        materialUnitId: row?.materialUnitId ?? "",
        name: res?.result?.name ?? "",
        code: res?.result?.code ?? "",
        status: res?.result?.status ?? 1,
        remarks: res?.result?.remarks ?? "",
      };
    }
    addDialog({
      title: `${title}单位信息`,
      props: {
        formInline: formInline
      },
      width: "44%",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message(`您${title}了单位`, {
            type: "success"
          });
          done();
          onSearch();
        }

        FormRef.validate(valid => {
          if (valid) {
            if (title === "新增") {
              createMaterialUnitApi(curData)
                .then((res) => {
				  if(res.code !== 200) {
				  	message(res.msg ?? "操作失败,请联系管理员", {
				  	  type: "error"
				  	});
				  	return
				  }
                  chores();
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
            } else {
              updateMaterialUnitApi(curData)
                .then((res) => {
				  if(res.code !== 200) {
				  	message(res.msg ?? "操作失败,请联系管理员", {
				  	  type: "error"
				  	});
				  	return
				  }
                  chores();
                })
                .catch(error => {
                  message(error.response.data.msg ?? "操作失败,请联系管理员", {
                    type: "error"
                  });
                });
            }
          }
        });
      }
    });
  }
  onMounted(async () => {
    onSearch();
  });

  function handleDelete(row) {
    delMaterialUnitApi({ materialUnitId: row.materialUnitId }).then((res) => {
	  if(res.code !== 200) {
	  	message(res.msg ?? "操作失败,请联系管理员", {
	  	  type: "error"
	  	});
	  	return
	  }
      message(`删除成功`, { type: "success" });
      onSearch();
    });
  }
  return {
    form,
    isShow,
    loading,
    columns,
    dataList,
    pagination,
    onSearch,
    resetForm,
    openDialog,
    handleSizeChange,
    handleCurrentChange,
    deviceDetection,
    handleDelete
  };
}
